import type { SwaggerParameter } from './types';

// 已经处理
const excludeFormat = [
  'bigdecimal',
  'double',
  'float',
  'int32',
  'int64',
  'binary'
];
export const description = (content: string, format?: string) => {
  if (format && !excludeFormat.includes(format)) {
    return `/** ${content}\n * @format: ${format}*/`;
  } else {
    return `/** ${content} */`;
  }
};

export const pathName = (str: string) => {
  if (/\d+$/.test(str) && str.length > 4) return 'id';
  const list = str.split(/[^a-zA-Z]/);
  let name = list
    .filter((item) => !!item)
    .map((item, index) => {
      if (index === 0) return item;
      const lower = item.toLowerCase();
      return lower[0].toUpperCase() + lower.slice(1);
    })
    .join('');
  if (/^[^a-z]/.test(name)) name = '_' + name;
  return name;
};

export const keyName = (str: string) => {
  if (/^\d/.test(str)) {
    return `"${str}"`;
  } else {
    return str;
  }
};

export const typeName = (str: string) => {
  switch (str) {
    case 'void':
    case 'string':
    case 'boolean':
    case 'number':
    case 'bigdecimal':
    case 'double':
    case 'long':
    case 'unknown':
    case 'never':
      return str;
    case 'object':
      return 'Record<string, string>';
    case 'Map':
      return 'Record<string, string>';
  }
  let name = str.replace(/[^\dA-Za-z\u4e00-\u9fa5]/g, '_');
  if (/^[a-z]/.test(str)) {
    name = name[0].toUpperCase() + name.slice(1);
  }
  if (/^[^A-Z]/.test(name)) {
    name = 'Type' + name;
  }
  return name;
};

export const interfaceName = (str: string) => {
  let name = str.replace(/[^\dA-Za-z\u4e00-\u9fa5]/g, '_');
  if (/[^\dA-Za-z\u4e00-\u9fa5]/.test(str)) {
    console.log(str, name);
  }
  if (/^[a-z]/.test(str)) {
    name = name[0].toUpperCase() + name.slice(1);
  }
  if (/^[^A-Z]/.test(name)) {
    name = 'Type' + name;
  }
  return name;
};

const nameMap = new Map<string, number>();
export const clearNameMap = () => {
  nameMap.clear();
};
export const apiName = (
  url: string,
  method: string,
  path: SwaggerParameter[] | undefined
) => {
  let name = url.replace(/^\/api/, '');
  name = name.replace(/^\/storefront\/v1/, '');
  name = name.replace(/^\/business\/v1/, '');
  if (path) {
    for (const item of path) {
      if (/\d+/.test(item.name) && item.name.length > 4) {
        name = name.replace(`{${item.name}}`, 'id');
      }
      name = name.replace(`{${item.name}}`, item.name);
    }
  }
  const wordList = name.split('/');
  name = wordList
    .filter((item) => !!item)
    .map((item) => {
      const str = item.replace(/[^\dA-Za-z\u4e00-\u9fa5/]/g, '');
      return str[0]?.toUpperCase() + str.slice(1);
    })
    .join('');
  name = method + name;
  const count = nameMap.get(name);
  if (count) {
    nameMap.set(name, count + 1);
    return name + count;
  } else {
    nameMap.set(name, 1);
    return name;
  }
};
